const path = require('path')
const mime = require('mime')
const fs = require('fs')

function myReadFile(file) {
    return new Promise((resolve, reject)=>{
        fs.readFile(file, (err, data)=>{
            if(err) {
                resolve('你访问的是一个文件夹，且文件夹里面没有index.html')
            } else {
                resolve(data)
            }
        })
    })
}

async function readStaticFile(filePathName) {
    let ext = path.parse(filePathName).ext
    let mimeType = mime.getType(ext) || 'text/html'
    // 判断文件是否存在
    let data
    if(fs.existsSync(filePathName)) {
        if(ext) {
            data = await myReadFile(filePathName)
        } else {
            data = await myReadFile(path.join(filePathName, '/index.html'))
        }
    } else {
        data = 'file or folder not found'
    }
    return {
        mimeType,
        data
    }
}

module.exports = readStaticFile